package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.services.SqfwPeopleInfoForAdminService;
import com.budwk.app.sqfw.vo.SqfwCenSusPaperVo;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import java.util.List;

/**
 * @program: wk-mini
 * @description: 人员信息（后台管理系统）
 * @author: LJT
 * @create: 2023-11-07 14:06
 **/
@IocBean
@At("/platform/sqfw/peopleInfo")
@ApiDefinition(tag = "人员信息")
@Slf4j
public class SqfwPeopleInfoForAdminController {

    @Inject
    private SqfwPeopleInfoForAdminService sqfwPeopleInfoForAdminService;

    /**
     * 人员信息列表查询（用于后台管理系统）
     */
    @At("/listForPeopleInfo")
    @Ok("json")
    @POST
    @ApiOperation(name = "人员信息列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_cenSusPaper.class
    )
    @ApiResponses(
            implementation = Sqfw_cenSusPaper.class
    )
    @SLog(tag = "人员信息列表查询", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> listForPeopleInfo(@Param("..") Sqfw_cenSusPaper bean, @Param("queryAll") String queryAll, @Param("queryTime") String queryTime, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = sqfwPeopleInfoForAdminService.buildConditionForQueryToCnd(bean, queryAll, queryTime, pageOrderName, pageOrderBy);
        Pagination pagination = sqfwPeopleInfoForAdminService.listPage(pageNo, pageSize, cnd);
        return Result.success(pagination);
    }

    /**
     * 根据条件下载Excel
     *
     * @param bean
     * @param pageOrderName
     * @param pageOrderBy
     * @return
     */
    @At("/generatePeopleInfoExcelByCond")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据条件下载excel")
    @ApiFormParams(
            implementation = Sqfw_cenSusPaper.class
    )
    @SLog(tag = "根据条件下载excel", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelCollByCond(@Param("..") Sqfw_cenSusPaper bean, @Param("queryAll") String queryAll, @Param("queryTime") String queryTime, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, @Param("fileIndex") Integer fileIndex, @Param("excelType") String excelType,@Param("startTime") String startTime,@Param("endTime") String endTime) {
        if (ObjectUtil.isEmpty(fileIndex)) {
            return Result.error("下载类型不能为空！");
        }
        List<String> ids = sqfwPeopleInfoForAdminService.getPdfExcelFileDownSumIdList(bean, queryAll, queryTime);
        if (ids.size() <= 0) {
            return Result.error("无匹配记录！");
        }
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwPeopleInfoForAdminService.createExcelAndUpload(ids, fileIndex, null,startTime,endTime);
        if (null == excelUrl) {
            return Result.error("无匹配记录！");
        }
        return Result.data(excelUrl);
    }

    /**
     * 勾选下载Excel
     *
     * @param ids
     */
    @At("/generatePeopleInfoExcelColl")
    @Ok("json")
    @POST
    @ApiOperation(name = "勾选下载Excel")
    @ApiFormParams(
            implementation = Sqfw_cenSusPaper.class
    )
    @SLog(tag = "勾选下载Excel", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generatePeopleInfoExcelColl(@Param("ids") List<String> ids, @Param("fileIndex") Integer fileIndex,@Param("startTime") String startTime,@Param("endTime") String endTime) {
        if (ObjectUtil.isEmpty(fileIndex)) {
            return Result.error("下载类型不能为空！");
        }
        if (ids.size() <= 0) {
            return Result.error("无匹配记录！");
        }
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwPeopleInfoForAdminService.createExcelAndUpload(ids, fileIndex, null,startTime,endTime);
        if (null == excelUrl) {
            return Result.error("无匹配记录！");
        }
        return Result.data(excelUrl);
    }


    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "导入住户信息")
    @ApiFormParams(
            value = {@ApiFormParam(name = "file", description = "文件对象名")},
            mediaType = "multipart/form-data"
    )
    @SaCheckLogin
    public Result<?> importHouseholdData(@Param("file") TempFile file) {
        return sqfwPeopleInfoForAdminService.importHouseholdData(file);
    }

    @At()
    @Ok("json")
    @PUT
    @ApiOperation(name = "单条数据更新")
    @ApiFormParams(implementation = SqfwCenSusPaperVo.class)
    @SLog(tag = "住户信息：单条数据更新", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> updateCenSusPaper(@Param("..") SqfwCenSusPaperVo paperVo) {
        log.info("SqfwPeopleInfoForAdminController updateCenSusPaper userName: {}, param: {}", SecurityUtil.getUserUsername(), JSONObject.toJSONString(paperVo));
        sqfwPeopleInfoForAdminService.updateCenSusPaper(paperVo);
        return Result.success();
    }

    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "新增人员信息")
    @ApiFormParams(implementation = SqfwCenSusPaperVo.class)
    @SLog(tag = "住户信息：新增人员信息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> insertCenSusPaper(@Param("..") SqfwCenSusPaperVo paperVo) {
        log.info("SqfwPeopleInfoForAdminController insertCenSusPaper userName: {}, param: {}", SecurityUtil.getUserUsername(), JSONObject.toJSONString(paperVo));
        sqfwPeopleInfoForAdminService.insertCenSusPaper(paperVo);
        return Result.success();
    }

    @At()
    @Ok("json")
    @DELETE
    @ApiOperation(name = "删除人员信息")
    @ApiFormParams(implementation = SqfwCenSusPaperVo.class)
    @SLog(tag = "住户信息：删除人员信息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> deleteById(@Param("id") String id) {
        log.info("SqfwPeopleInfoForAdminController deleteById userName: {}, param: {}", SecurityUtil.getUserUsername(), id);
        // 查询出人员信息表记录
        Sqfw_cenSusPaper sqfwCenSusPaper = sqfwPeopleInfoForAdminService.fetch(id);
        if (null == sqfwCenSusPaper) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        // 删除人员信息表记录
        sqfwPeopleInfoForAdminService.deleteById(id);
        // 更新summary表a7字段记录
        if (Strings.isNotBlank(sqfwCenSusPaper.getSqfwSummaryId())) {

        }
        return Result.success();
    }

    /**
     * @param ids        选择记录iD
     * @param bean       对象信息
     * @param queryAll   查询参数
     * @param queryTime  查询时间
     * @param queryEntry 查询入口
     * @return
     */
    @At("/checkParamFromHouseInfo")
    @Ok("json")
    @POST
    @ApiOperation(name = "检测excel数据")
    @ApiFormParams(
            implementation = Sqfw_cenSusPaper.class
    )
    @SLog(tag = "检测excel数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> checkParamFromHouseInfo(@Param("ids") List<String> ids, @Param("..") Sqfw_cenSusPaper bean, @Param("queryAll") String queryAll, @Param("queryTime") String queryTime, @Param("queryEntry") String queryEntry,@Param("startTime") String startTime,@Param("endTime") String endTime,@Param("fileIndex") Integer fileIndex) {
        return Result.data(sqfwPeopleInfoForAdminService.checkParamFromHouseInfo(ids, bean, queryAll, queryTime, queryEntry,startTime,endTime,fileIndex));
    }

    /**
     * 勾选下载Excel
     *
     * @param fileIndex 文件索引key
     */
    @At("/generatePeopleInfoTemplateDownload")
    @Ok("json")
    @POST
    @ApiOperation(name = "住户信息模板下载")
    @ApiFormParams(
            implementation = Sqfw_cenSusPaper.class
    )
    @SLog(tag = "住户信息模板下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generatePeopleInfoTemplateDownload(@Param("fileIndex") Integer fileIndex) {
        if (ObjectUtil.isEmpty(fileIndex)) {
            return Result.error("下载类型不能为空！");
        }
        String excelUrl = sqfwPeopleInfoForAdminService.generatePeopleInfoTemplateDownload(fileIndex);
        if (null == excelUrl) {
            return Result.error("无匹配记录！");
        }
        return Result.data(excelUrl);
    }


}
